package ExchangeMail;

use Log;

#Console utility help
#Usage:
# send <subject> <toEmailAddress> <user> <password> <domain>
# list <user> <password> <domain>
# delete <messageid> <user> <password> <domain>

sub sendMessage
{
	my ($subject,$data,$toEmailAddress,$user,$pass,$domain)=@_;
	my $rname="";
	my @a=('0'..'9','a'..'z');
	for(0..15)
	{
		$rname.=$a[int(rand(@a))];
	}
	$rname.='.tmp';
	open FF,">$rname";
	print FF $data;
	close FF;
	Log::_debug("Send message call\n\tExchangeClient.exe send \"$subject\" \"$toEmailAddress\" \"$user\" \"$pass\" \"$domain\" < $rname\n");
	my $res=`ExchangeClient.exe send "$subject" "$toEmailAddress" "$user" "$pass" "$domain" < $rname`;
	`del $rname`;
	return 1;
}

sub listMessages
{
	my ($user,$pass,$domain)=@_;
	Log::_debug("List messages call\n\tExchangeClient.exe list \"$user\" \"$pass\" \"$domain\"\n");
	my $res=`ExchangeClient.exe list "$user" "$pass" "$domain"`;
	my @messages=();
	my $collect={};
	for(split(/\n/,$res))
	{
		s/^\s+|\s+$//g;
		if($_ eq '.')
		{
			$collect->{'headed'}=undef;
			push @messages,$collect;
			$collect={};
		}else{
			if(!defined $collect->{'raw'})
			{
				$collect->{'raw'}=[];
			}
			push @{$collect->{'raw'}},$_;
			if(!defined $collect->{'headed'})
			{
				if(/./)
				{
					if(/(.*?)\s*\:\s*(.*)/)
					{
						$collect->{$1}=$2;
					}
				}else{
					$collect->{'headed'}=1;
				}
			}else{
				if(!defined $collect->{'body'})
				{
					$collect->{'body'}=[];
				}
				push @{$collect->{'body'}},$_;
			}
		}
	}
	return \@messages;
}

sub deleteMessage
{
	my ($messageid,$user,$pass,$domain)=@_;
	Log::_debug("Delete message call\n\tExchangeClient.exe delete \"$messageid\" \"$user\" \"$pass\" \"$domain\"\n");
	my $res=`ExchangeClient.exe delete "$messageid" "$user" "$pass" "$domain"`;
	if($res=~/OK/)
	{
		return 1;
	}else{
		return 0;
	}
}

1;